package org.jeecg.modules.API.until;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class RabbitmqProduUntil {

    public static Map<String, Channel> m_map_exchange_channel = new HashMap<>();

    public static boolean initExchange(String exchangeName) throws IOException, TimeoutException {
        if (m_map_exchange_channel.get(exchangeName) == null) {
            ConnectionFactory factory = new ConnectionFactory();
            //设置RabbitMQ相关信息
            factory.setHost("localhost");
            //创建一个新的连接
            Connection connection = factory.newConnection();
            //创建一个通道
            Channel channel = connection.createChannel();

            if(exchangeName.equals("YGMD")){
                channel.exchangeDeclare(exchangeName, "fanout");
            }else {
                channel.exchangeDeclare(exchangeName, "topic");
            }
            m_map_exchange_channel.put(exchangeName, channel);
        }
        return true;
    }

    public static boolean productMsg(String exchange_name, String routing_key, Object obj) throws IOException, TimeoutException {
        //if (initRoutingKey(exchange_name, queue_name, routing_key) == true) {
        if (initExchange(exchange_name) == true){
            String message = obj.toString();
            if(exchange_name.equals("YGMD")){
                m_map_exchange_channel.get(exchange_name).basicPublish(exchange_name, "", null, obj.toString()
                        .getBytes("UTF-8"));
            }else{
                m_map_exchange_channel.get(exchange_name).basicPublish(exchange_name, routing_key, null, obj.toString()
                        .getBytes("UTF-8"));
            }
            return true;
        }
        return false;
        //}
        //return true;
    }
  }
